package com.xkdx.guangguang.fragment.map;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.application.MyApplication;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.Shop;

public class SingleShopMapFragment extends Fragment {
	private static String TAG = "SingleShopMapFragment";

	MapView mMapView = null;
	BMapManager mBMapMan = null;
	public MKMapViewListener mMapListener = null;
	FrameLayout mMapViewContainer = null;
	List<Shop> shopList = new ArrayList<Shop>();
	Button shut, daohang;
	EditText indexText = null;
	String shopID;
	int index = 0;
	int position = -1;
	LocationClient mLocClient;
	MyLocationOverlay myLocationOverlay = null;
	LocationData locData = null;
	String startAddress = null;
	LocationListener mLocationListener = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	// String url_shopInfo = Static.address +
	// "informationInterface/getInfoListByShop.php";
	List<Object> parentList = new ArrayList<Object>();
	boolean isFinish = false;
	/**
	 * 圆心经纬度坐标
	 */

	// 存放overlayitem
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	// 存放overlay图片
	public List<Drawable> res = new ArrayList<Drawable>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		final int size = getArguments().getInt("size");
		for (int i = 0; i < size; i++) {
			shopList.add((Shop) getArguments().getSerializable("shop" + i));
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.single_shop_map, container, false);
		setMap(view);

		return view;
	}

	private void setMap(View view) {
		if (mMapView != null) {
			mMapView.refresh();
		} else {
			mMapView = (MapView) view.findViewById(R.id.bmapsView);
			mMapView.setLongClickable(true);
			mMapView.getController().setZoom(14);
			mMapView.getController().enableClick(true);
			mMapView.setBuiltInZoomControls(true);
		}

		mMapView.getController().setCenter(new GeoPoint((int) (IConstants.lat * 1e6), (int) (IConstants.lon * 1e6)));
		init(view);
		MyApplication app = (MyApplication) getActivity().getApplication();
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(getActivity());
			app.mBMapManager.init(MyApplication.strKey, new MyApplication.MyGeneralListener());
		}
		mLocClient = new LocationClient(getActivity());

		mLocClient.registerLocationListener(myListener);

		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(false);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(5000);
		mLocClient.setLocOption(option);
		mLocClient.start();

		mMapListener = new MKMapViewListener() {

			@Override
			public void onMapMoveFinish() {
				// TODO Auto-generated method stub
				Log.d("hjtest", "hjtest" + "onMapMoveFinish");

			}

			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null) {
					title = mapPoiInfo.strText;
					Toast.makeText(getActivity(), title, Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
				// TODO Auto-generated method stub
				Log.d("hjtest", "hjtest" + "getmap OK");
			}

			@Override
			public void onMapAnimationFinish() {
				// TODO Auto-generated method stub
				Log.d("hjtest", "hjtest" + "onMapAnimationFinish");

			}

			@Override
			public void onMapLoadFinish() {
				// TODO Auto-generated method stub
				isFinish = true;
			}
		};

		// mMapView.regMapViewListener(Location.getInstance().mBMapManager,
		// mMapListener);

		// 添加标记
		Drawable marker = getActivity().getResources().getDrawable(R.drawable.iconmarka);
		for (int i = 0; i < shopList.size(); i++) {
			if (shopList.get(i).getLatitude() != null && shopList.get(i).getLongitude() != null) {
				int lat = (int) (Double.valueOf(shopList.get(i).getLatitude()) * 1e6);

				int lon = (int) (Double.valueOf(shopList.get(i).getLongitude()) * 1e6);

				OverlayItem item = new OverlayItem(new GeoPoint(lat, lon), "item" + i, "item" + i);
				item.setMarker(marker);
				mGeoList.add(item);
			}
		}

		mMapView.getOverlays().clear();
		// 定位当前位置
		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
		myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();

		OverlayTest ov = new OverlayTest(marker, mMapView, getActivity(), shopList);
		for (OverlayItem item : mGeoList) {
			ov.addItem(item);
		}
		mMapView.getOverlays().add(ov);
		mMapView.refresh();

	}

	private void init(View view) {
		shut = (Button) view.findViewById(R.id.map_back);
		daohang = (Button) view.findViewById(R.id.daohang);
		shut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentManager fm = getFragmentManager();
				fm.popBackStack();

			}
		});
		daohang.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startNavi(v);

			}
		});

	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	public void onDestroy() {
		mMapView.destroy();
		super.onDestroy();
	}

	private void initMapView() {
		mMapView.setLongClickable(true);
		// mMapController.setMapClickEnable(true);
		// mMapView.setSatellite(false);
	}

	class OverlayTest extends ItemizedOverlay {
		private Context mContext = null;
		PopupOverlay pop = null;
		private Button mBtn = null;
		Toast mToast = null;
		List<Shop> list;

		public OverlayTest(Drawable defaultMarker, MapView mapView, Context context, final List<Shop> list) {
			super(defaultMarker, mapView);
			this.mContext = context;
			this.list = list;
		}

		public boolean onTap(int index) {
			position = index;
			pop = new PopupOverlay(mMapView, new PopupClickListener() {

				@Override
				public void onClickedPopup(int index) {
					// Log.i(TAG, "index-->" + position);
					getFragmentManager().popBackStack();
				}
			});

			View view = LayoutInflater.from(mContext).inflate(R.layout.shoplistpopview, null);
			initPopView(index, view);

			Bitmap map = IConstants.getBitmapFromView(view);
			pop.showPopup(map, mGeoList.get(index).getPoint(), 32);

			return true;
		}

		public boolean onTap(GeoPoint pt, MapView mapView) {
			if (pop != null) {
				pop.hidePop();
			}
			return false;
		}
	}

	public void initPopView(final int index2, View view) {
		TextView tv = (TextView) view.findViewById(R.id.map_name);

		tv.setText(shopList.get(index2).getShopName());

	}

	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			myLocationOverlay.setData(locData);
			if (mMapView != null && mLocClient != null) {
				mMapView.refresh();
				if (shopList.get(0).getLatitude() != null) {
					mMapView.getController().animateTo(
							new GeoPoint((int) (Double.valueOf(shopList.get(0).getLatitude()) * 1e6), (int) (Double
									.valueOf(shopList.get(0).getLongitude()) * 1e6)));
				}
				mLocClient.unRegisterLocationListener(myListener);
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	@Override
	public void onStop() {
		if (mLocClient != null) {
			mLocClient.stop();
		}
		super.onStop();

	}

	private void startNavi(View view) {
		if (getActivity() != null && shopList != null && shopList.size() != 0) {
			GeoPoint pt1 = new GeoPoint(((int) (locData.latitude * 1e6)), (int) (locData.longitude * 1e6));
			GeoPoint pt2 = new GeoPoint((int) (Double.valueOf(shopList.get(index).getLatitude()) * 1E6),
					(int) (Double.valueOf(shopList.get(index).getLongitude()) * 1E6));
			// 构建 导航参数
			NaviPara para = new NaviPara();
			para.startPoint = pt1;
			para.startName = "从这里开始";
			para.endPoint = pt2;
			para.endName = "到这里结束";

			try {
				BaiduMapNavigation.openBaiduMapNavi(para, getActivity());

			} catch (BaiduMapAppNotSupportNaviException e) {
				e.printStackTrace();
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
				builder.setTitle("提示");
				builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						BaiduMapNavigation.GetLatestBaiduMapApp(getActivity());
					}
				});

				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

				builder.create().show();
			}

		} else {
			Toast.makeText(getActivity(), "未获得商场坐标", Toast.LENGTH_SHORT).show();
		}
	}

}
